package model

import (
	"time"
	"user_srv/basic/config"
)

// 用户匹配关系表
type XqUserMatches struct {
	Id        int64     `gorm:"column:id;type:bigint;primaryKey;not null;" json:"id"`
	UserId1   int64     `gorm:"column:user_id1;type:bigint;comment:用户1ID;not null;" json:"user_id1"`           // 用户1ID
	UserId2   int64     `gorm:"column:user_id2;type:bigint;comment:用户2ID;not null;" json:"user_id2"`           // 用户2ID
	MatchTime time.Time `gorm:"column:match_time;type:timestamp;default:CURRENT_TIMESTAMP;" json:"match_time"` // 匹配时间
	IsActive  int8      `gorm:"column:is_active;type:tinyint(1);comment:是否有效;default:1;" json:"is_active"`     // 是否有效
	CreatedAt time.Time `gorm:"column:created_at;type:timestamp;default:CURRENT_TIMESTAMP;" json:"created_at"`
	UpdatedAt time.Time `gorm:"column:updated_at;type:timestamp;default:CURRENT_TIMESTAMP;" json:"updated_at"`
}

func (x *XqUserMatches) TableName() string {
	return "xq_user_matches"
}

func (x *XqUserMatches) Create() error {
	return config.DB.Create(&x).Error
}

func (x *XqUserMatches) Delete(where XqUserMatches) error {
	return config.DB.Where(where).Delete(&x).Error
}

func (x *XqUserMatches) Update(where XqUserMatches) error {
	return config.DB.Where(where).Updates(&x).Error
}

func (x *XqUserMatches) GetByUserIds(userId1, userId2 int64) (*XqUserMatches, error) {
	var match XqUserMatches
	err := config.DB.Where("((user_id1 = ? AND user_id2 = ?) OR (user_id1 = ? AND user_id2 = ?)) AND is_active = 1",
		userId1, userId2, userId2, userId1).First(&match).Error
	return &match, err
}

func (x *XqUserMatches) GetByMatchId(matchId int64) (*XqUserMatches, error) {
	var match XqUserMatches
	err := config.DB.Where("id = ? AND is_active = 1", matchId).First(&match).Error
	return &match, err
}

func (x *XqUserMatches) ListByUserId(userId int64, limit, offset int) ([]XqUserMatches, error) {
	var matches []XqUserMatches
	query := config.DB.Where("(user_id1 = ? OR user_id2 = ?) AND is_active = 1", userId, userId)
	if limit > 0 {
		query = query.Limit(limit)
	}
	if offset > 0 {
		query = query.Offset(offset)
	}
	err := query.Order("match_time DESC").Find(&matches).Error
	return matches, err
}

// 检查两个用户是否已匹配
func (x *XqUserMatches) IsMatched(userId1, userId2 int64) bool {
	var count int64
	config.DB.Model(&XqUserMatches{}).Where("((user_id1 = ? AND user_id2 = ?) OR (user_id1 = ? AND user_id2 = ?)) AND is_active = 1",
		userId1, userId2, userId2, userId1).Count(&count)
	return count > 0
}

// 获取匹配的另一方用户ID
func (x *XqUserMatches) GetMatchedUserId(userId int64) int64 {
	if x.UserId1 == userId {
		return x.UserId2
	}
	return x.UserId1
}
